﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Loki.Model
{
	/// <summary>
	/// Application model base class
	/// </summary>
	public class ServiceModel : LokiObject, IDisposable
	{
		#region Log and Errors
		/// <summary>
		/// Logger name ; must be redefined in derived classes
		/// </summary>
		/// <value></value>
		protected override string LoggerName
		{
			get
			{
				return "Loki.Core.ApplicationModel";
			}
		}

		#endregion

		#region Service registering
		private Dictionary<Guid, IService> _Services = new Dictionary<Guid, IService>();
		public void RegisterService<TServiceInterface>(TServiceInterface P_Service) where TServiceInterface : IService
		{
			Log.InfoFormat("Service {0} - ID {1} registered as {2}", P_Service.Name, P_Service.ID, typeof(TServiceInterface).Name);
			_Services[P_Service.ID] = P_Service;
		}

		public TServiceInterface GetService<TServiceInterface>() where TServiceInterface : IService
		{
			return (TServiceInterface)_Services.Values.FirstOrDefault(x => x is TServiceInterface);
		}

		#endregion

		#region Disposable
		/// <summary>
		/// Releases all resources used by an instance of the <see cref="ServiceModel" /> class.
		/// </summary>
		/// <remarks>
		/// This method calls the virtual <see cref="Dispose(bool)" /> method, passing in <strong>true</strong>, and then suppresses 
		/// finalization of the instance.
		/// </remarks>
		public void Dispose()
		{
			Dispose(true);
			GC.SuppressFinalize(this);
		}

		/// <summary>
		/// Releases unmanaged resources before an instance of the <see cref="ServiceModel" /> class is reclaimed by garbage collection.
		/// </summary>
		/// <remarks>
		/// This method releases unmanaged resources by calling the virtual <see cref="Dispose(bool)" /> method, passing in <strong>false</strong>.
		/// </remarks>
		~ServiceModel()
		{
			Dispose(false);
		}

		/// <summary>
		/// Releases the unmanaged resources used by an instance of the <see cref="ServiceModel" /> class and optionally releases the managed resources.
		/// </summary>
		/// <param name="disposing"><strong>true</strong> to release both managed and unmanaged resources; <strong>false</strong> to release only unmanaged resources.</param>
		protected virtual void Dispose(bool disposing)
		{
			if (disposing)
			{
				foreach (IService L_Service in _Services.Values)
				{
					L_Service.Dispose();
				}
			}
		}
		#endregion
	}
}
